package com.io.AIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>AIO, 也叫 NIO2.0 是一种异步非阻塞的通信方式</p>
 * <p>NIO 通过多路复用器轮询注册的通道，从而实现非阻塞效果，同时也说明了NIO是同步的。</p>
 * <p>既然AIO是非阻塞的，哪它又是如何实现异步非阻塞的呢？</p>
 * <p>AIO 引入了异步通道的概念 AsynchronousServerSocketChannel 和 AsynchronousSocketChannel</p>
 *
 * @author hjj
 * @create 2019-11-24 20:57
 */
public class AIOServer {
    private ExecutorService executorService;        // 线程池
    private AsynchronousChannelGroup threadGroup;    // 通道组
    public AsynchronousServerSocketChannel asynServerSocketChannel;  // 服务器通道

    public void start(int port) {
        try {
            executorService = Executors.newCachedThreadPool();
            // 创建通道组
            threadGroup = AsynchronousChannelGroup.withCachedThreadPool(executorService, 1);
            // 创建服务器通道
            asynServerSocketChannel = AsynchronousServerSocketChannel.open(threadGroup);
            // 进行绑定
            asynServerSocketChannel.bind(new InetSocketAddress(port));
            asynServerSocketChannel.accept(this, new AIOServerHandler());
            Thread.sleep(Integer.MAX_VALUE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
